import { GeneratedContent, ContentGenerationRequest, ContentGenerationResponse } from '@/types';
import { PLATFORM_MAP } from '@/constants/platforms';
import { PLATFORM_PROMPTS } from '@/constants/ai-config';
import { aiService } from '@/lib/ai-service';

export class ContentGenerator {
  /**
   * 生成多平台文案
   */
  async generateMultiPlatformContent(request: ContentGenerationRequest): Promise<ContentGenerationResponse> {
    const { originalContent, selectedPlatforms } = request;
    const generatedContents: GeneratedContent[] = [];

    // 并行生成各平台内容
    const generatePromises = selectedPlatforms.map(async (platformId) => {
      try {
        const content = await this.generatePlatformContent(originalContent, platformId);
        return content;
      } catch (error) {
        console.error(`生成${platformId}平台内容失败:`, error);
        // 返回错误占位内容
        return this.generateErrorFallbackContent(platformId, originalContent);
      }
    });

    const results = await Promise.allSettled(generatePromises);
    
    results.forEach((result) => {
      if (result.status === 'fulfilled' && result.value) {
        generatedContents.push(result.value);
      }
    });

    return {
      originalContent,
      generatedContents,
      timestamp: Date.now()
    };
  }

  /**
   * 为特定平台生成内容
   */
  async generatePlatformContent(originalContent: string, platformId: string): Promise<GeneratedContent> {
    const platform = PLATFORM_MAP[platformId];
    if (!platform) {
      throw new Error(`未找到平台: ${platformId}`);
    }

    // 构建平台特定的提示词
    const prompt = this.buildPlatformPrompt(originalContent, platformId);
    
    // 调用AI服务生成内容
    const aiGeneratedContent = await aiService.generateContent(prompt);
    
    // 解析AI生成的内容
    const parsedContent = this.parseAIResponse(aiGeneratedContent, platform);
    
    return {
      platform: platformId,
      title: parsedContent.title,
      content: parsedContent.content,
      hashtags: parsedContent.hashtags,
      features: platform.features
    };
  }

  /**
   * 构建平台特定的提示词
   */
  private buildPlatformPrompt(originalContent: string, platformId: string): string {
    const platformPrompt = PLATFORM_PROMPTS[platformId as keyof typeof PLATFORM_PROMPTS];
    const platform = PLATFORM_MAP[platformId];
    
    return `
${platformPrompt}

原始内容：
"""
${originalContent}
"""

请严格按照以下格式输出：
【标题】这里是标题内容
【正文】这里是正文内容
【标签】#标签1 #标签2 #标签3（如果适用）

注意：
- 标题要简洁有吸引力，不超过${platform.name === '微博' ? '20' : '35'}字
- 正文不超过${platform.maxLength}字
- 保持原始内容的核心意思
- 体现${platform.name}平台的特色：${platform.features.join('、')}
    `;
  }

  /**
   * 解析AI响应内容
   */
  private parseAIResponse(aiResponse: string, platform: any): {
    title: string;
    content: string;
    hashtags?: string[];
  } {
    // 尝试解析结构化输出
    const titleMatch = aiResponse.match(/【标题】(.+?)(?=【|$)/s);
    const contentMatch = aiResponse.match(/【正文】(.+?)(?=【|$)/s);
    const hashtagsMatch = aiResponse.match(/【标签】(.+?)(?=【|$)/s);

    let title = titleMatch ? titleMatch[1].trim() : '';
    let content = contentMatch ? contentMatch[1].trim() : '';
    let hashtags: string[] = [];

    // 如果没有找到结构化输出，使用智能分割
    if (!title || !content) {
      const fallback = this.intelligentParse(aiResponse, platform);
      title = title || fallback.title;
      content = content || fallback.content;
    }

    // 解析标签
    if (hashtagsMatch) {
      hashtags = hashtagsMatch[1]
        .split(/[#\s]+/)
        .filter(tag => tag.trim().length > 0)
        .map(tag => tag.trim());
    }

    // 确保内容长度符合平台限制
    if (content.length > platform.maxLength) {
      content = content.substring(0, platform.maxLength - 3) + '...';
    }

    // 如果没有标题，从内容中提取
    if (!title) {
      title = this.extractTitleFromContent(content, platform);
    }

    return {
      title: title || '智能生成的标题',
      content: content || '内容生成中，请稍后重试...',
      hashtags: hashtags.length > 0 ? hashtags : undefined
    };
  }

  /**
   * 智能解析非结构化AI响应
   */
  private intelligentParse(response: string, platform: any): { title: string; content: string } {
    const lines = response.split('\n').filter(line => line.trim());
    
    if (lines.length === 0) {
      return {
        title: '请重新生成内容',
        content: '生成失败，请重试'
      };
    }

    // 第一行作为标题，其余作为内容
    const title = lines[0].trim().replace(/^[【\[\(（"']|[】\]\)）"']$/g, '');
    const content = lines.slice(1).join('\n').trim();

    return {
      title: title.substring(0, 35), // 限制标题长度
      content: content
    };
  }

  /**
   * 从内容中提取标题
   */
  private extractTitleFromContent(content: string, platform: any): string {
    // 取前30个字符作为标题
    const title = content.substring(0, 30);
    const lastPunctuation = Math.max(
      title.lastIndexOf('。'),
      title.lastIndexOf('！'),
      title.lastIndexOf('？'),
      title.lastIndexOf('.'),
      title.lastIndexOf('!'),
      title.lastIndexOf('?')
    );
    
    if (lastPunctuation > 10) {
      return title.substring(0, lastPunctuation);
    }
    
    return title + (title.length === 30 ? '...' : '');
  }

  /**
   * 生成错误回退内容
   */
  private generateErrorFallbackContent(platformId: string, originalContent: string): GeneratedContent {
    const platform = PLATFORM_MAP[platformId];
    const shortContent = originalContent.length > 100 
      ? originalContent.substring(0, 100) + '...' 
      : originalContent;

    return {
      platform: platformId,
      title: `${platform.name}专属内容标题`,
      content: `${shortContent}\n\n[内容已针对${platform.name}平台特性进行优化]`,
      features: platform.features
    };
  }

  /**
   * 预处理原始内容
   */
  private preprocessContent(content: string): string {
    return content
      .trim()
      .replace(/\s+/g, ' ') // 合并多个空格
      .replace(/\n\s*\n/g, '\n'); // 合并多个换行
  }

  /**
   * 生成内容摘要
   */
  generateSummary(content: string, maxLength: number = 100): string {
    if (content.length <= maxLength) {
      return content;
    }
    
    // 尝试在句号、感叹号、问号处截断
    const sentences = content.split(/[。！？.!?]/);
    let summary = '';
    
    for (const sentence of sentences) {
      if (summary.length + sentence.length <= maxLength - 3) {
        summary += sentence + '。';
      } else {
        break;
      }
    }
    
    return summary || content.substring(0, maxLength - 3) + '...';
  }
}

// 导出单例实例
export const contentGenerator = new ContentGenerator();